import React, { Component } from 'react';
import { Alert, View, Image, StyleSheet, PixelRatio ,TouchableOpacity} from 'react-native';
import { Container, Content, Card, CardItem, Text, Body, Button, List, ListItem } from 'native-base';
import moment from 'moment';
import ImageShow from '../components/comm/ImageShow';
export default class RepairInfo extends Component {
    constructor(props) {
        super(props);
        this.state = {
            info: {},
            list: [],
            modalVisible:false
        };
    }
    componentDidMount() {
        const { navigation } = this.props;
        url = global.urltype + global.urlpath + ":" + global.urlport + "/api/MachineWX/getInfo";
        para = 'wxid=' + navigation.getParam('wxid');
        url += '?' + para;
        return fetch(url, {
            method: 'GET',
            headers: {
                'Authorization': global.token
            }
        }).then(response => response.json())
            .then(json => {
                if (json.recode == 1) {
                    this.setState({ info: json.data });
                    this.loadList(navigation.getParam('wxid'));
                }
            })
            .catch(error => {
                console.error(error);
            });

    }
    loadList = (wxid) => {
        //查询维修记录
        url = global.urltype + global.urlpath + ":" + global.urlport + "/api/MachineWXDetail/getList";
        para = 'wxid=' + wxid;
        url += '?' + para;
        return fetch(url, {
            method: 'GET',
            headers: {
                'Authorization': global.token
            }
        }).then(responselist => responselist.json())
            .then(jsonlist => {
                if (jsonlist.recode == 1) {
                    this.setState({ list: jsonlist.list  });
                }
            })
            .catch(error => {
                console.error(error);
            });
    }
    goback = () => {
        const { navigate, goBack, state } = this.props.navigation;
        state.params.callback();
        this.props.navigation.goBack();
    }
    handle = (status) => {
        url = global.urltype + global.urlpath + ":" + global.urlport + "/api/MachineWX/updateStatus";
        $para = 'wxid=' + this.state.info.wxid + '&wxstatus=' + status;
        return fetch(url, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded',
                'Authorization': global.token
            },
            body: $para
        })
            .then(response => response.json())
            .then(json => {
                if (json) {
                    Alert.alert("处理成功", "撤回成功", [
                        {
                            text: '确认',
                            onPress: () => {
                                this.goback();
                            }
                        }
                    ]);
                } else {
                    Alert.alert("更新失败", "更新失败", [
                        {
                            text: '确认'
                        }
                    ]);
                }
            })
            .catch(error => {
                console.error(error);
            });
    }
    handleToggleModalVisible=()=>{
        this.setState({
            modalVisible:!this.state.modalVisible
        })
    }
    delListItem=(id)=>{
        listArray = this.state.list;
        for (var i = 0; i < listArray.length; i++) {
            if (listArray[i].id == id){
                listArray.splice(i,1);
                break;
            }
        }
        return listArray;

    }
    handleDelWxInfo=(id)=>{
        Alert.alert("作废记录", "确认作废这条记录吗？", [
            { text: '取消' },
            {
                text: '确认', onPress: () => {
                    url = global.urltype + global.urlpath + ":" + global.urlport + "/api/MachineWXDetail/Delete";
                    para = 'id=' + id;

                    return fetch(url, {
                        method: 'POST',
                        headers: {
                            'Content-Type': 'application/x-www-form-urlencoded',
                            'Authorization': global.token
                        },
                        body: para
                    }).then(responselist => responselist.json())
                        .then(jsonlist => {
                            if (jsonlist.recode == 1) {
                                this.setState({ list: this.delListItem(id)})
                            }
                            alert(jsonlist.msg);
                        })
                        .catch(error => {
                            console.error(error);
                        });
                }
            },
        ])
    }
    render() {
        const { navigation } = this.props;
        if (this.state.info.wxStatus == "NEW") {
            action = <CardItem>
                <Button transparent onPress={() => { 
                    Alert.alert("撤销", "确认撤销吗？", [
                        {text:'取消'},
                        {
                            text: '确认',
                            onPress: () => {
                                this.handle('CN')
                            }
                        }
                    ]);
                 }}>
                    <Text>撤回</Text>
                </Button>
            </CardItem>
        } else if (this.state.info.wxStatus == "WX") {
            action = <CardItem>
                <Button transparent onPress={() => {
                    navigation.navigate('AddNewRec',
                        {
                            wxid: navigation.getParam('wxid'),
                            callback: () => {
                                this.loadList(this.state.info.wxid);
                            }
                        })
                }}>
                    <Text> 添加记录</Text>
                </Button>
            </CardItem>
        } else {
            action = <CardItem />
        }
        let imgArray = [];

        if (JSON.stringify(this.state.info) != '{}') {
            //图片
            imgArray = this.state.info.imgPath.split("^");
            info = <Content>
                <Card>
                    <CardItem header>
                        <Text>{this.state.info.wxid}</Text>
                    </CardItem>
                    <CardItem>
                        <Body>
                            <Text>
                                设备编号:{this.state.info.macID}
                            </Text>
                            <Text>
                                设备名称:{this.state.info.macName}
                            </Text>
                            <Text>
                                设备型号:{this.state.info.modelNo}
                            </Text>
                            <Text>
                                问题描述
                            </Text>
                            <Text>
                                {this.state.info.mtncContent}
                            </Text>
                        </Body>
                    </CardItem>
                    <CardItem footer>
                        <Text>{moment(this.state.info.mtncDate).format("YYYY-MM-DD HH:mm:ss")}</Text>
                    </CardItem>
                    {action}
                    <CardItem style={infoStyle.ImgContainer}>
                        {
                            imgArray.map((itemObj, idx) => {
                                return (
                                    <View style={[infoStyle.Img, infoStyle.ImgContainer, { margin: 10 }]}>
                                        <TouchableOpacity onPress={this.handleToggleModalVisible}>
                                            <Image style={infoStyle.Img} key={idx}
                                                source={{ uri: global.urltype + global.urlpath + ":" + global.urlport + itemObj }}
                                            />
                                        </TouchableOpacity>
                                        
                                    </View>
                                )
                            })
                        }
                    </CardItem>
                </Card>
                <List style={{ borderTopColor: "#ddd", borderTopWidth: 1 }}>
                    {this.state.list.map((itemObj, idx) => {
                        return (
                            <ListItem key={idx} style={[itemObj.kind == "WX" ? infoStyle.wx : infoStyle.new
                                , itemObj.appliant == global.userid ? infoStyle.mine:{}
                                                        ]}>
                                <Body>
                                    <TouchableOpacity onLongPress={() => { this.handleDelWxInfo(itemObj.id)}}>
                                        <Text style={{ color: "#666" }}>{moment(itemObj.createTime).format("YYYY-MM-DD HH:mm:ss")}</Text>
                                        <Text>描述:{itemObj.wxContent}</Text>
                                    </TouchableOpacity>
                                </Body>
                            </ListItem>
                        )
                    })}
                </List>

                <ImageShow
                    modalVisible={this.state.modalVisible}
                    toggleModalVisible={this.handleToggleModalVisible}
                    imgPath={this.state.info.imgPath}
                />
            </Content>
        } else {
            info = <Content><Text></Text></Content>
        }
        return (
            <Container>
                {info}
            </Container>
        );
    }
}

const infoStyle = StyleSheet.create({
    ImgContainer: {
        borderColor: '#9B9B9B',
        borderWidth: 1 / PixelRatio.get(),
        alignItems: 'center',
        flexDirection: "row",
        flexWrap: "wrap"
    },
    Img: {
        width: 66,
        height: 66
    },
    new: {
        backgroundColor: "#f5f5f5"
    },
    wx: {
        backgroundColor: "#dff",
        flexDirection: "column",
        alignItems: "flex-end",
    },
    mine:{
        backgroundColor:"#ff4"
    }
});